<template>
    <div class="container">
        <el-form :model="searchForm" ref="searchFormRef" label-width="80px" class="mb-4"
            style="display: flex; align-items: center; flex-wrap: wrap;">
            <el-row :gutter="20" style="flex: 1; display: flex;">
                <el-col :span="6">
                    <el-form-item label="产品编号">
                        <el-input v-model="searchForm.productId" placeholder="输入产品编号" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="产品名称">
                        <el-input v-model="searchForm.productName" placeholder="输入产品名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="仓库">
                        <el-input v-model="searchForm.warehouseName" placeholder="输入仓库名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="批次号">
                        <el-input v-model="searchForm.batchNo" placeholder="输入批次号" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-button type="primary" @click="mockData" style="margin-left: 10px;">
                查询
            </el-button>
            <el-button @click="handleReset" style="margin-left: 10px;">
                重置
            </el-button>
        </el-form>

        <div class="export-button-container">
            <el-button @click="batchExport">导出</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" ref="tableRef" style="width: 100%">
            <el-table-column type="selection">
                <template #default="scope">
                    <el-checkbox :disabled="getDisabled(scope.row)" :model-value="scope.selected"
                        @change="(val: boolean) => handleCheckboxChange(val, scope.row)"></el-checkbox>
                </template>
            </el-table-column>
            <el-table-column type="index" label="序号" style="width: 80px;">
                <template #default="scope">
                    {{ scope.row.stock_quantity === 0 ? '×' : scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="product_id" label="产品编号" />
            <el-table-column prop="product_name" label="产品名称" />
            <el-table-column prop="spec" label="产品规格" />
            <el-table-column prop="category" label="产品类别" />
            <el-table-column prop="storage_unit" label="存储单位" />
            <el-table-column prop="warehouse_name" label="仓库名称" />
            <el-table-column prop="location_name" label="库位名称" />
        </el-table>
    </div>
    <div style="display: flex; align-items: center; gap: 8px;">
        <el-button @click="selectAll">全选</el-button>
        <el-button @click="reverseSelect">反选</el-button>
        <el-button @click="batchHandle">批量操作</el-button>
        <div style="flex: 1;"></div>
        <el-pagination v-model:current-page="searchForm.pageIndex" v-model:page-size="searchForm.pageSize"
            :page-sizes="[1, 10, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="searchForm.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElTable, ElMessage } from 'element-plus';
import { saveAs } from 'file-saver';
import { KongaUrl } from '@/axios/axiosHelp'
interface TableRow {
    product_id: string;
    product_name: string;
    spec: string;
    category: string;
    storage_unit: string;
    warehouse_name: string;
    location_name: string;
    stock_quantity: number;
    // 其他字段根据实际接口补充
}

const searchForm = reactive({
    productId: '',
    productName: '',
    warehouseName: '',
    batchNo: '',
    pageIndex: 1,
    pageSize: 15,
    totalPage: 0,
    totalCount: 0,
});

const tableData = ref<TableRow[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>();

onMounted(() => {
    mockData();
});

// 辅助函数：处理禁用状态
const getDisabled = (row: TableRow) => {
    return row.stock_quantity === 0 || row.stock_quantity === null || row.stock_quantity === undefined;
};

const mockData = async () => {
    try {
        const res = await KongaUrl<{
            code: number;
            msg: string;
            data: {
                list: TableRow[];
                totalPage: number;
                totalCount: number;
            };
        }>("wangjunlong/api/Inventory/InventoryQuser", {
            params: {
                Product_id: searchForm.productId,
                Product_name: searchForm.productName,
                Warehouse_name: searchForm.warehouseName,
                Batch_no: searchForm.batchNo,
                PageIdex: searchForm.pageIndex,
                PageSize: searchForm.pageSize,
            }
        });

        if (res.data.code === 210) {
            tableData.value = res.data.data.list;
            searchForm.totalPage = res.data.data.totalPage;
            searchForm.totalCount = res.data.data.totalCount;
        } else {
            console.error('查询失败:', res.data.msg);
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        console.error('请求出错:', error);
        ElMessage.error('网络请求失败，请检查连接');
    }
};

const handleSizeChange = (size: number) => {
    searchForm.pageSize = size;
    mockData();
};

const handleCurrentChange = (page: number) => {
    searchForm.pageIndex = page;
    mockData();
};

const handleReset = () => {
    searchForm.productId = '';
    searchForm.productName = '';
    searchForm.warehouseName = '';
    searchForm.batchNo = '';
    searchForm.pageIndex = 1;
    mockData();
};

// 全选
const selectAll = () => {
    tableRef.value?.toggleAllSelection();
};

// 反选
const reverseSelect = () => {
    const allRows = tableData.value;
    const selected = tableRef.value?.getSelectionRows() || [];
    const allKeys = allRows.map(row => row.product_id);
    const reverseKeys = allKeys.filter(id => !selected.some(s => s.product_id === id));

    reverseKeys.forEach(id => {
        const row = allRows.find(row => row.product_id === id);
        if (row) tableRef.value?.toggleRowSelection(row);
    });
};

// 批量操作
const batchHandle = () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择数据');
        return;
    }
    console.log('批量操作数据:', selected);
    // 这里添加实际业务逻辑（如调用接口）
};

// 处理复选框选择状态改变
const handleCheckboxChange = (val: boolean, row: TableRow) => {
    tableRef.value?.toggleRowSelection(row, val);
};

// 批量导出功能
const batchExport = async () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }
    const productIds = selected.map(item => item.product_id);

    try {
        const res = await KongaUrl.get('/wangjunlong/api/Inventory/ExportOrderList', {
            params: {
                Product_id: productIds
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '批量库存数据.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.mb-4 {
    margin-bottom: 16px;
}

.export-button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
}
</style>